<?php

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Event;
class Center_OrderController extends CenterController
{
    protected $orderService;

    public function __construct(OrderService $orderService)
    {
        parent::__construct();
        $this->orderService = $orderService;
    }
    /**
     * 商品订单列表
     */
    public function listOrders()
    {
        $params = Input::all();
        $page = Input::get('page', 1);
        $rows_per_page = Input::get('rows_per_page', PaginationHelper::ROWS_PER_PAGE);
        $offset = ($page - 1) * $rows_per_page;
        // invoice
        // district
        $order = Post::leftJoin('post_order', 'post_order.post_id', '=', 'posts.id')
            ->leftJoin('order', 'post_order.order_id', '=', 'order.id')
            ->select(
                'posts.id',
                'posts.type', 
                'posts.status',
                'order.state',
                'order.title', 
                'order.created_at', 
                'order.updated_at',  
                'order.id as order_id', 
                'order.order_no', 
                'order.price', 
                'order.qty')
            ->whereNotNull('order_no')
            ->where('order.state', Order::STATE_INIT)
            ->where('order.user_id', $this->user->id)
	        ->orderBy('order.updated_at', 'DESC')
	        ->take($rows_per_page)
	        ->skip($offset)
            ->get();
        $orderArr = $order->toArray();
        foreach ($orderArr as &$orderItem) {
            $orderItem['status_name'] = UtilsHelper::getPostStatusStr($orderItem['status']);
            $orderItem['unit_price'] = round($orderItem['price'] / $orderItem['qty']) . "";
            $orderItem['price'] = round($orderItem['price']);
            $orderItem['type_name'] = UtilsHelper::getTypeStr($orderItem['type']);
            $company = CompanyServer::where('order_id', $orderItem['order_id'])->first();
            if ($company) {
                $orderItem['invoice'] = $company['invoice'] == 'Y' ? true : false;
                $orderItem['address'] = sprintf(
                    "%s %s %s",
                    AreaHelper::areaCodeToName($company['province']),
                    AreaHelper::areaCodeToName($company['city']),
                    AreaHelper::areaCodeToName($company['district'])
                );
            } else {
                $orderItem['invoice'] = false;
                $orderItem['address'] = "全国";
            }
            $transitions = [];
            $transitions[] = array(
                'to_cancel' => route('center.question.to_cancel', array(
                    'id' => $orderItem['id']
                ))
            );
            $transitions[] = array(
                'to_pay_with_wallet' => route('center.question.pay.wallet', array(
                    'id' => $orderItem['id']
                ))
            );
            // $transitions[] = array(
            //     'to_pay_with_money' => route('center.question.pay.money', array(
            //         'id' => $orderItem['id']
            //     ))
            // );
            $orderItem['transitions'] = $transitions;
        }
        
        return $this->makeView('center.order.list', $orderArr);
    }

    /**
     * 钱包支付
     *
     * @param post_id $id            
     */
    public function walletPay($id)
    {
        $question = Post::find($id);
        if (! is_a($question, 'Post')) {
            return $this->makeView('errors.404', '该订单不存在', 404);
        }
        if ($question->status != Post::STATUS_WAIT_PAY) {
            return $this->makeView('errors.400', '状态不正确', 400);
        }
        $wallet = Wallet::find(Auth::user()->id);
        $order = $question->getOrder($id);
        $price = $order->price;
        if ($wallet->money < $price) {
            return $this->makeView('errors.400', '钱包余额不足', 400);
        }
        try {
            $post = Input::get('description');
            DB::transaction(function ($input) use ($question, $wallet, $order, $price, $post) {
                $wallet->money = $wallet->money - $price;
                $wallet->save();
                $question->status = Post::STATUS_NEW;
                $question->save();
                $order->state = Order::STATE_PAID;
                $order->pay_status = Order::PAY_STATUS_PAIS;
                $order->save();
                $record = new WalletTransaction();
                $record->user_id = Auth::user()->id;
                $record->type = WalletTransaction::TYPE_QUESTION;
                $record->direction = WalletTransaction::DIRECTION_OUT;
                $record->associate_id = $order->id;
                $record->status = WalletTransaction::STATUS_WAIT;
                $record->sum = $price;
                $record->order_no = $order->order_no;
                $record->description = "钱包支付".$post;
                $record->save();
            });
            Event::fire('pay_post', [$question]);
        } catch (Exception $ex) {
            Log::error($ex);
            return $this->makeView('errors.503', '支付失败，请稍后再试。', 503);
        }
        return $this->makeView('gener.200', '付款成功', 200);
    }

    /**
     * 直接支付：通过微信，或者其他手段直接支付成功以后调用这个函数
     *
     * @param post_id $id            
     */
    public function moneyPay($id)
    {
        $question = Post::find($id);
        if (! is_a($question, 'Post')) {
            return $question;
        }
        if ($question->status != Post::STATUS_WAIT_PAY) {
            return $this->makeView('errors.400', '状态不正确', 400);
        }
        $wallet = Wallet::find(Auth::user()->id);
        $order = $question->getOrder($id);
        try {
            $post = Input::get('description');
            DB::transaction(function ($input) use ($question, $order) {
                $question->status = Post::STATUS_NEW;
                $question->save();
                $order->state = Order::STATE_PAID;
                $order->pay_status = Order::PAY_STATUS_PAIS;
                $order->save();
            });
        } catch (Exception $ex) {
            Log::error($ex);
            return $this->makeView('errors.503', '支付失败，请稍后再试。', 503);
        }
        return $this->makeView('gener.201', '付款成功', 201);
    }
    
    /**
     * 创建RewardOrder订单
     */
    public function orderReward()
    {

        $input = Input::all();
        $rules = array(
            'lawyer_id' => 'required',
            'money' => 'required',
        );
        $messages = array(
            'lawyer_id.required' => 'lawyer_id不能为空',
            'money.required' => 'money不能为空',

        );
        $validator = Validator::make($input, $rules, $messages);
        if($validator->fails()){
            return $this->makeView('errors.400', $validator->errors(), 400);
        }
        $lawyer_id = Input::get('lawyer_id');
        $money   = Input::get('money');
        $order = $this->orderService->createOrder(
            Order::ORDER_TYPE_REWARD,
            $lawyer_id,
            $money,
            Auth::user()->id,
            Order::STATE_INIT,
            '打赏',
            isset(Auth::user()->phone) ? Auth::user()->phone : ''
        );
        return $this->makeView('general.200',['order_id' => $order->id],200);
    }
}
